import { PAGE_TAB_INFORS, PAGE_TAB_CUNRUNT_INDEX } from './enums'
import { useTabStore } from './stores/tabs'
import { logger } from '@/apps/logger'
import type { tabinfos } from './types'
import { getPageTabAppUrls } from './routers'

enum loadState {
  success = '=success=success=',
  fail = '=fail=fail='
}
// 类型校验
function localStorageGet<T>(
  key: string,
  parser: (key: string) => T
): { state: loadState; value?: T } {
  const _ = localStorage.getItem(key)
  if (_) {
    return { state: loadState.success, value: parser(_) }
  } else {
    return { state: loadState.fail }
  }
}

function initPageTabApp() {
  // if(process.env ==="delelopment"){

  // }
  logger.gradient(`Init PageTab App.`)
  const store = useTabStore()
  /* -------------------------------- 初始化页面标签 -------------------------------- */
  const _1 = localStorageGet<tabinfos[]>(PAGE_TAB_INFORS, (str: string) => {
    try {
      return JSON.parse(str)
    } catch (error) {
      logger.error(`Can not load tabs from localstoryge as follwing reasons: ${error}`)
    }
  })
  if (_1.state === loadState.success) {
    const tabsRes = _1.value as tabinfos[]
    store.reloadFrom(tabsRes)
  }

  /* -------------------------------- 初始化当前标签 -------------------------------- */
  const _2 = localStorageGet(PAGE_TAB_CUNRUNT_INDEX, (str: string) => {
    try {
      return parseInt(str)
    } catch (error) {
      logger.error(`Can not load tab index from localstoryge as follwing reasons: ${error}`)
    }
  })
  if (_2.state === loadState.success) {
    let index = _2.value as number
    const len = store.tabs.length
    logger.debug(`Set current tab index as: ${index}`)
    if (index > len - 1) {
      logger.warn(
        `PageIndexExceeds: The index value of the record exceeds the total number of page labels..`
      )
      index = store.tabs.length - 1
    }
    store.select(index)
  }
}
/**需要插入 vue-router 的路由 */

export { initPageTabApp, getPageTabAppUrls }
